package com.tree.common.config.i18n.util;

import com.tree.common.util.SpringContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;

import java.util.Locale;

/**
 * @ClassName com.demo.common.i18n.util
 * Description: <类功能描述>. <br>
 * <p>
 * <使用说明>
 * </p>
 * @Author tree
 * @Date 2019-05-24 23:49
 * @Version 1.0
 */
public class MessageUtil {
    private static Logger logger = LoggerFactory.getLogger(MessageUtil.class);
    private static final Locale DEFAULT_LOCALE = Locale.CHINA;

    private static MessageSource getMessageSource(){
        return SpringContextHolder.getBean("localMessage");
    }

    public static Locale getLocale(){
        Locale locale = LocaleContextHolder.getLocale();
        return locale!= null ? locale : DEFAULT_LOCALE;
    }

    public static String getMessage(String code, Locale locale , Object[] params){
        String message = getMessageSource().getMessage(code,(params!= null ? params:null),locale);
        return message;

    }

    public static String getMessage(String code){
        return getMessage(code,new Object[]{});
    }

    public static String getMessage(int code){
        return getMessage(String.valueOf(code),new Object[]{});
    }

    public static String getMessage(String code, Object[] params){
        String message = null;
        try{
            Locale locale = getLocale();
            MessageSource messageSource = getMessageSource();
            message = messageSource.getMessage(code,(params!=null?params:null),locale);
        }catch (Exception e){

        }
        return message;
    }

    public static String getMessage(String messageCode, String param){
        return getMessage(messageCode,new Object[]{param});
    }

    public static String getMessage(String messageCode, Object param){
        return getMessage(messageCode,new Object[]{param});
    }

}
